import { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import {
  Plus,
  Trash2,
  Edit2,
  ExternalLink,
  Download,
  Upload,
  Bot,
  Save,
  X,
  AlertCircle,
  CheckCircle2,
  Loader2,
} from 'lucide-react';
import { agentsAPI, type Agent } from '@/lib/apiClient';

/**
 * 智能体管理页面
 * 支持添加、编辑、删除智能体，使用数据库 API
 */
export default function AgentManager() {
  const [agents, setAgents] = useState<Agent[]>([]);
  const [isAdding, setIsAdding] = useState(false);
  const [editingId, setEditingId] = useState<string | null>(null);
  const [formData, setFormData] = useState({
    name: '',
    url: '',
    description: '',
    icon: 'Bot',
  });
  const [message, setMessage] = useState<{ type: 'success' | 'error'; text: string } | null>(null);
  const [loading, setLoading] = useState(false);

  // 加载智能体列表
  useEffect(() => {
    loadAgents();
  }, []);

  const loadAgents = async () => {
    try {
      setLoading(true);
      const response = await agentsAPI.getAll();
      setAgents(response.agents);
      // 触发自定义事件，通知侧边栏更新
      window.dispatchEvent(new Event('agents-updated'));
    } catch (error) {
      console.error('Failed to load agents:', error);
      showMessage('error', '加载失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  const showMessage = (type: 'success' | 'error', text: string) => {
    setMessage({ type, text });
    setTimeout(() => setMessage(null), 3000);
  };

  const handleAdd = () => {
    setIsAdding(true);
    setFormData({ name: '', url: '', description: '', icon: 'Bot' });
  };

  const handleEdit = (agent: Agent) => {
    setEditingId(agent.id);
    setFormData({
      name: agent.name,
      url: agent.url,
      description: agent.description || '',
      icon: agent.icon || 'Bot',
    });
  };

  const handleCancel = () => {
    setIsAdding(false);
    setEditingId(null);
    setFormData({ name: '', url: '', description: '', icon: 'Bot' });
  };

  const handleSave = async () => {
    if (!formData.name.trim() || !formData.url.trim()) {
      showMessage('error', '请填写智能体名称和URL');
      return;
    }

    try {
      if (editingId) {
        // 更新
        await agentsAPI.update(editingId, formData);
        showMessage('success', '智能体更新成功');
      } else {
        // 添加
        await agentsAPI.create(formData);
        showMessage('success', '智能体添加成功');
      }
      
      handleCancel();
      await loadAgents();
    } catch (error) {
      showMessage('error', error instanceof Error ? error.message : '操作失败');
    }
  };

  const handleDelete = async (id: string) => {
    if (!confirm('确定要删除这个智能体吗？')) {
      return;
    }

    try {
      await agentsAPI.delete(id);
      await loadAgents();
      showMessage('success', '智能体删除成功');
    } catch (error) {
      showMessage('error', error instanceof Error ? error.message : '删除失败');
    }
  };

  const handleExport = async () => {
    try {
      const response = await agentsAPI.getAll();
      const data = JSON.stringify(response.agents, null, 2);
      const blob = new Blob([data], { type: 'application/json' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `feng-admin-agents-${new Date().toISOString().split('T')[0]}.json`;
      a.click();
      URL.revokeObjectURL(url);
      showMessage('success', '导出成功');
    } catch (error) {
      console.error('Export failed:', error);
      showMessage('error', '导出失败');
    }
  };

  const handleImport = () => {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = 'application/json';
    input.onchange = async (e) => {
      const file = (e.target as HTMLInputElement).files?.[0];
      if (!file) return;

      try {
        const text = await file.text();
        const importedAgents = JSON.parse(text);
        
        if (!Array.isArray(importedAgents)) {
          throw new Error('数据格式错误');
        }

        // 逐个导入智能体
        for (const agent of importedAgents) {
          try {
            await agentsAPI.create({
              name: agent.name,
              url: agent.url,
              description: agent.description,
              icon: agent.icon,
            });
          } catch (err) {
            console.error('Failed to import agent:', agent.name, err);
          }
        }
        
        await loadAgents();
        showMessage('success', '导入成功');
      } catch (error) {
        showMessage('error', error instanceof Error ? error.message : '导入失败');
      }
    };
    input.click();
  };

  const handleReset = async () => {
    if (!confirm('确定要删除所有智能体吗？此操作无法撤销！')) {
      return;
    }

    try {
      // 删除所有智能体
      for (const agent of agents) {
        await agentsAPI.delete(agent.id);
      }
      await loadAgents();
      showMessage('success', '已清空所有智能体');
    } catch (error) {
      console.error('Reset failed:', error);
      showMessage('error', '重置失败');
    }
  };

  return (
    <div className="space-y-6">
      {/* Page header */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold">智能体管理</h1>
          <p className="text-muted-foreground">管理你的AI智能体，支持添加自定义智能体</p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" size="sm" onClick={handleExport}>
            <Download className="mr-2 h-4 w-4" />
            导出
          </Button>
          <Button variant="outline" size="sm" onClick={handleImport}>
            <Upload className="mr-2 h-4 w-4" />
            导入
          </Button>
          <Button variant="outline" size="sm" onClick={handleReset}>
            重置
          </Button>
          <Button onClick={handleAdd}>
            <Plus className="mr-2 h-4 w-4" />
            添加智能体
          </Button>
        </div>
      </div>

      {/* Message */}
      {message && (
        <Card className={message.type === 'error' ? 'border-destructive' : 'border-green-500'}>
          <CardContent className="flex items-center gap-2 p-4">
            {message.type === 'success' ? (
              <CheckCircle2 className="h-5 w-5 text-green-500" />
            ) : (
              <AlertCircle className="h-5 w-5 text-destructive" />
            )}
            <span>{message.text}</span>
          </CardContent>
        </Card>
      )}

      {/* Add/Edit Form */}
      {(isAdding || editingId) && (
        <Card>
          <CardHeader>
            <CardTitle>{editingId ? '编辑智能体' : '添加新智能体'}</CardTitle>
            <CardDescription>填写智能体的基本信息</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="grid gap-2">
              <label className="text-sm font-medium">名称 *</label>
              <Input
                placeholder="例如：ChatGPT助手"
                value={formData.name}
                onChange={(e) => setFormData({ ...formData, name: e.target.value })}
              />
            </div>
            <div className="grid gap-2">
              <label className="text-sm font-medium">URL *</label>
              <Input
                placeholder="例如：https://chat.openai.com"
                value={formData.url}
                onChange={(e) => setFormData({ ...formData, url: e.target.value })}
              />
            </div>
            <div className="grid gap-2">
              <label className="text-sm font-medium">描述</label>
              <Input
                placeholder="简短描述这个智能体"
                value={formData.description}
                onChange={(e) => setFormData({ ...formData, description: e.target.value })}
              />
            </div>
            <div className="grid gap-2">
              <label className="text-sm font-medium">图标名称</label>
              <Input
                placeholder="Lucide图标名称，例如：Bot, MessageSquare"
                value={formData.icon}
                onChange={(e) => setFormData({ ...formData, icon: e.target.value })}
              />
              <p className="text-xs text-muted-foreground">
                查看可用图标：
                <a
                  href="https://lucide.dev/icons"
                  target="_blank"
                  rel="noopener noreferrer"
                  className="ml-1 text-primary underline"
                >
                  lucide.dev/icons
                </a>
              </p>
            </div>
            <div className="flex gap-2">
              <Button onClick={handleSave}>
                <Save className="mr-2 h-4 w-4" />
                保存
              </Button>
              <Button variant="outline" onClick={handleCancel}>
                <X className="mr-2 h-4 w-4" />
                取消
              </Button>
            </div>
          </CardContent>
        </Card>
      )}

      {/* Agents List */}
      {loading && agents.length === 0 ? (
        <div className="flex items-center justify-center py-12">
          <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
        </div>
      ) : agents.length === 0 && !isAdding ? (
        <Card>
          <CardContent className="flex flex-col items-center justify-center py-12">
            <Bot className="h-12 w-12 text-muted-foreground" />
            <p className="mt-4 text-lg font-medium">还没有智能体</p>
            <p className="text-sm text-muted-foreground">点击"添加智能体"按钮创建你的第一个智能体</p>
          </CardContent>
        </Card>
      ) : (
        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
          {agents.map((agent) => (
            <Card key={agent.id} className="relative">
              <CardHeader>
                <div className="flex items-start justify-between">
                  <div className="flex items-center gap-2">
                    <Bot className="h-5 w-5 text-primary" />
                    <CardTitle className="text-lg">{agent.name}</CardTitle>
                  </div>
                  <Badge variant="secondary">智能体</Badge>
                </div>
                {agent.description && (
                  <CardDescription>{agent.description}</CardDescription>
                )}
              </CardHeader>
              <CardContent>
                <div className="space-y-3">
                  <div className="flex items-center gap-2 text-sm text-muted-foreground">
                    <ExternalLink className="h-4 w-4" />
                    <a
                      href={agent.url}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="truncate hover:text-primary hover:underline"
                    >
                      {agent.url}
                    </a>
                  </div>
                  <div className="flex gap-2">
                    <Button
                      variant="outline"
                      size="sm"
                      className="flex-1"
                      onClick={() => handleEdit(agent)}
                    >
                      <Edit2 className="mr-2 h-4 w-4" />
                      编辑
                    </Button>
                    <Button
                      variant="outline"
                      size="sm"
                      className="flex-1"
                      onClick={() => handleDelete(agent.id)}
                    >
                      <Trash2 className="mr-2 h-4 w-4" />
                      删除
                    </Button>
                  </div>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}
    </div>
  );
}
